<?php namespace App\Domain\ErrBook\Service;


use App\Domain\ErrBook\Model\ErrBook;
use App\Domain\Item\Model\Item;
use Illuminate\Support\Facades\DB;

class ErrBookServiceImpl implements ErrBookService
{
    public function updateErrBook($bookUid, $doorid, $readerid, $status)
    {
        $errbook = ErrBook::where('BookUID', $bookUid)
            ->first();
        if (!$errbook) {
          return ErrBook::create([
               'BookUID' => $bookUid,
               'ReaderID' => $readerid,
               'DoorID' => $doorid,
               'InMacState' => $status,
               'LastUseDate' => time()
           ]);
        } else {
          return $errbook->update([
                'BookUID' => $bookUid,
                'ReaderID' => $readerid,
                'DoorID' => $doorid,
                'InMacState' => $status,
                'LastUseDate' => time()
            ]);
        }
    }

    public function deleteErrBook($rfid){
        DB::beginTransaction();
        try {
            //更新bookstatus
            $item=Item::leftJoin('TagInfo as t','t.Barcode','=','Items.BarCode')
                ->where('t.rUID',$rfid)
                ->first();
            if($item){
                $item->update(['bookstatus'=>0]);
            }
            //删除异常书
            ErrBook::where('BookUID',$rfid)->delete();

            DB::commit();
        }catch (\Exception $e) {

            DB::rollback();
            return false;
        }
        return true;

    }

}